// 设备订阅与取消订阅路由
import express, { Request, Response } from 'express';
import { AppDataSource } from '../../config/database';
import {AccessToken} from "../../entity/Accesstoken";
import { MideaDevice } from '../../entity/MideaDevice';
import { XiaomiDevice } from '../../entity/XiaomiDevice';

const mockSubscribeRouter = express.Router();
mockSubscribeRouter.use(express.json());


// 美的设备订阅
mockSubscribeRouter.post('/midea/device/subscribe', async (req: Request, res: Response): Promise<void> => {
  const { reqId, applianceCode } = req.body;
  const accessToken = req.headers.authorization?.replace('Bearer ', '');
  const clientId = req.headers.clientid as string;

  if (!accessToken || !clientId) {
    res.status(400).json({
      reqId,
      code: 400,
      message: '缺少必要请求头: Authorization 或 ClientId'
    });
  }

  try {
    const tokenRepo = AppDataSource.getRepository(AccessToken);
    const tokenRecord = await tokenRepo.findOne({
      where: { token: accessToken, appId: clientId }
    });

    if (!tokenRecord || tokenRecord.expiresAt < new Date()) {
      res.status(401).json({
        reqId,
        code: 1006,
        message: '用户验证失败'
      });
      return;
    }

    const mideaDeviceRepo = AppDataSource.getRepository(MideaDevice);
    const device = await mideaDeviceRepo.findOne({ 
      where: { did: applianceCode, userId: tokenRecord.userId }
    });

    if (!device) {
      throw new Error('设备不存在');
    }

    device.subscribed = true;
    await mideaDeviceRepo.save(device);

    res.json({ reqId, code: 200, message: '订阅成功' });
  } catch (err: any) {
    const code = err.message.includes('设备不存在') ? 1300 : 1006;
    res.status(code === 1300 ? 404 : 401).json({
      reqId,
      code,
      message: err.message
    });
  }
});

// 美的设备取消订阅
mockSubscribeRouter.post('/midea/device/subscribe/cancel', async (req: Request, res: Response): Promise<void> => {
  const { reqId, applianceCode } = req.body;
  const accessToken = req.headers.authorization?.replace('Bearer ', '');
  const clientId = req.headers.clientid as string;

  if (!accessToken || !clientId) {
    res.status(400).json({
      reqId,
      code: 400,
      message: '缺少必要请求头: Authorization 或 ClientId'
    });
  }

  try {
    const tokenRepo = AppDataSource.getRepository(AccessToken);
    const tokenRecord = await tokenRepo.findOne({
      where: { token: accessToken, appId: clientId }
    });

    if (!tokenRecord || tokenRecord.expiresAt < new Date()) {
      res.status(401).json({
        reqId,
        code: 1006,
        message: '用户验证失败'
      });
      return;
    }

    const mideaDeviceRepo = AppDataSource.getRepository(MideaDevice);
    const device = await mideaDeviceRepo.findOne({ 
      where: { did: applianceCode, userId: tokenRecord.userId }
    });

    if (!device) {
      throw new Error('设备不存在');
    }

    device.subscribed = false;
    await mideaDeviceRepo.save(device);

    res.json({ reqId, code: 200, message: '取消订阅成功' });
  } catch (err: any) {
    const code = err.message.includes('设备不存在') ? 1300 : 1006;
    res.status(code === 1300 ? 404 : 401).json({
      reqId,
      code,
      message: err.message
    });
  }
});

// 小米设备订阅
mockSubscribeRouter.post('/xiaomi/device/subscribe', async (req: Request, res: Response): Promise<void> => {
  const { did } = req.body;
  const accessToken = req.headers.access_token as string;
  const appId = req.headers.app_id as string;

  if (!accessToken || !appId) {
    res.status(400).json({
      code: 400,
      message: '缺少必要请求头: access_token 或 app_id'
    });
  }

  try {
    const tokenRepo = AppDataSource.getRepository(AccessToken);
    const tokenRecord = await tokenRepo.findOne({
      where: { token: accessToken, appId }
    });

    if (!tokenRecord || tokenRecord.expiresAt < new Date()) {
      res.status(401).json({
        code: 903,
        message: '授权过期'
      });
      return;
    }

    const xiaomiDeviceRepo = AppDataSource.getRepository(XiaomiDevice);
    const device = await xiaomiDeviceRepo.findOne({ 
      where: { did, userId: tokenRecord.userId }
    });

    if (!device) {
      throw new Error('设备不存在');
    }

    device.subscribed = true;
    await xiaomiDeviceRepo.save(device);

    res.json({ code: 200, message: '订阅成功' });
  } catch (err: any) {
    const code = err.message.includes('设备不存在') ? 1 : 903;
    res.status(code === 1 ? 404 : 401).json({
      code,
      message: err.message
    });
  }
});

// 小米设备取消订阅
mockSubscribeRouter.post('/xiaomi/device/subscribe/cancel', async (req: Request, res: Response): Promise<void> => {
  const { did } = req.body;
  const accessToken = req.headers.access_token as string;
  const appId = req.headers.app_id as string;

  if (!accessToken || !appId) {
    res.status(400).json({
      code: 400,
      message: '缺少必要请求头: access_token 或 app_id'
    });
  }

  try {
    const tokenRepo = AppDataSource.getRepository(AccessToken);
    const tokenRecord = await tokenRepo.findOne({
      where: { token: accessToken, appId }
    });

    if (!tokenRecord || tokenRecord.expiresAt < new Date()) {
      res.status(401).json({
        code: 903,
        message: '授权过期'
      });
      return;
    }

    const xiaomiDeviceRepo = AppDataSource.getRepository(XiaomiDevice);
    const device = await xiaomiDeviceRepo.findOne({ 
      where: { did, userId: tokenRecord.userId }
    });

    if (!device) {
      throw new Error('设备不存在');
    }

    device.subscribed = false;
    await xiaomiDeviceRepo.save(device);

    res.json({ code: 200, message: '取消订阅成功' });
  } catch (err: any) {
    const code = err.message.includes('设备不存在') ? 1 : 903;
    res.status(code === 1 ? 404 : 401).json({
      code,
      message: err.message
    });
  }
});

export default mockSubscribeRouter;
